/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-03-24 10:07:36
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-26 15:33:51
 * @Description: file content
 */

import { Service } from "egg";
import { Redis } from "ioredis";

/** 系统 配置 */
export default class SysConfigService extends Service {
  // redisDb2: Redis;
  /**
   *获取配置对象。实现内置的redis缓存的。
   *
   * @param {boolean} [strongRefresh=false]
   * @return {*}
   * @memberof SysConfigService
   */
  async getConfigObject(strongRefresh = false) {
    if (!strongRefresh) {
      const redis = await this.ctx.service.redis.getRedisDb(undefined, 2);
      const redisConfigObject = await redis.get(this.app.const.redis.dingAdminSysConfig);
      if (redisConfigObject) {
        return JSON.parse(redisConfigObject);
      }
    }
    const data = await this.ctx.model.Sys.Config.findAll({
      raw: true,
      attributes: ["key", "value"],
    });
    const ret = {};
    data.forEach((item) => {
      ret[item.key] = JSON.parse(item.value);
    });
    await this.refreshRedisConfig(ret);
    return ret;
  }

  /** 配置对象存在redis中。并在更新数据库配置时触发同步更新。 */
  async refreshRedisConfig(configObj) {
    const redis = await this.ctx.service.redis.getRedisDb(undefined, 2);
    await redis.set(this.app.const.redis.dingAdminSysConfig, JSON.stringify(configObj));
    //   "EX",
    //   this.config.jwtLogin.expires
    // console.log("set config.");
  }
}
